package graphic;

import graphic.dialogs.ClientConfigurationDialog;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import core.Client;
import dbms.DBCheckAndConfigurationFunctions;

public class ConnectionPanel extends JPanel {

	protected static ConnectionPanel CONNECTIONPANEL;
	
	JTextField ip;
	JTextField port;
	
	JTextField userId;
	JPasswordField password;
	
	public ConnectionPanel() {
		
		super(new FlowLayout(FlowLayout.CENTER));
		
		this.connection();
		
		super.validate();
	}
	
	public void connection()
	{
		this.ip = new JTextField("127.0.0.1");
		this.port = new JTextField("7000");
		
		JButton connect = new JButton("Connect!");
		connect.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				
				if(Client.getInstance().connect(ConnectionPanel.this.ip.getText(), Integer.parseInt(ConnectionPanel.this.port.getText())))
					ConnectionPanel.this.logining();
			}
		});
		
		super.add(ip);
		super.add(port);
		super.add(connect);
	}
	
	public void logining()
	{
		if(!DBCheckAndConfigurationFunctions.isDBConfigured())
			new ClientConfigurationDialog();
		else
		{
			super.removeAll();

			this.userId = new JTextField("");
			this.password = new JPasswordField("");
			
			JButton login = new JButton("Login!");
			login.addActionListener(new ActionListener() {
				
				@Override
				public void actionPerformed(ActionEvent e) {
					if(Client.getInstance().login(ConnectionPanel.this.userId.getText(), ConnectionPanel.this.password.getText()))
						System.out.println("CONNECTION PANEL: LOGIN TRUE");
				}
			});
			
			super.add(userId);
			super.add(password);
			super.add(login);
			
			super.repaint();
			super.revalidate();
		}
	}
	
	public static ConnectionPanel getInstance()
	{
		if(CONNECTIONPANEL == null) CONNECTIONPANEL = new ConnectionPanel();
		return CONNECTIONPANEL;
	}
}
